<template>
  <!-- 餐品表单 -->
  <up-subsection :list="list" mode="subsection" :current="curNow" @change="sectionChange"></up-subsection>
  <view class="content">
    <view class="main" v-show="curNow == 0">
      <uni-forms ref="formRef" :model="food" labelWidth="80px" :rules="rules">
        <uni-forms-item label="餐品照片" name="icon">
          <view class="avatar">
            <img @click="selectImage" :src="imageUrl" alt="">
          </view>
        </uni-forms-item>
        <uni-forms-item label="餐品名称" name="name" required>
          <uni-easyinput v-model="food.name" placeholder="请输入餐品名称" />
        </uni-forms-item>
        <uni-forms-item label="价格" name="price" required>
          <uni-easyinput v-model="food.price" placeholder="请输入价格" />
        </uni-forms-item>
        <uni-forms-item label="餐品描述" name="dec" required>
          <uni-easyinput v-model="food.dec" placeholder="请输入餐品描述" />
        </uni-forms-item>
        <uni-forms-item label="打包费" name="packPrice" required>
          <uni-easyinput v-model="food.packPrice" placeholder="请输入打包费" />
        </uni-forms-item>
        <uni-forms-item label="配送费" name="sendPrice" required>
          <uni-easyinput v-model="food.sendPrice" placeholder="请输入配送费" />
        </uni-forms-item>
      </uni-forms>
      <button type="primary" @click="submit">{{ isEditMode ? '更新' : '提交' }}</button>
    </view>

    <!-- 餐品列表 -->
    <view class="food-list" v-if="curNow == 1">
      <up-swipe-action>
        <up-swipe-action-item v-for="(item, index) in foodList" :key="item.id" :options="options1"
          @click="handleAction(item, $event)">
          <view class="food-item">
            <image :src="item.icon" class="food-image"></image>
            <view class="food-info">
              <text class="food-name">{{ item.name }}</text>
              <text class="food-desc">{{ item.dec || '暂无描述' }}</text>
              <view class="price-row">
                <text class="price-item">¥{{ item.price }}</text>
                <text class="price-item">配送费: {{ item.sendPrice }}元</text>
                <text class="price-item">打包费: {{ item.packPrice }}元</text>
              </view>
            </view>
          </view>
        </up-swipe-action-item>
      </up-swipe-action>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { upFood, updataFood, deleteFood } from "@/api/user/index";
import useUserStore from '@/store/modules/user'
import { getUserInfo } from "@/api/user/index";

import config from '@/config'

const baseUrl = config.baseUrl
const userStore = useUserStore()

// 顶部 tab栏配置（使用新数组保持响应式）
const originalTabs = [{ name: '餐品上传' }, { name: '餐品列表' }]
const list = ref([...originalTabs])
const curNow = ref(0);

const sectionChange = (index) => {
  // 切换时重置编辑状态
  if (isEditMode.value) {
    list.value = [...originalTabs]
    resetForm()
  }
  curNow.value = index
}

onMounted(() => {
  loadDefaultAvatar();
});

// 表单相关
const formRef = ref(null);
const rules = {
  name: {
    rules: [{
      required: true,
      errorMessage: '请输入餐品名称'
    }]
  },
  price: {
    rules: [{
      required: true,
      errorMessage: '请输入价格'
    }, {
      pattern: /^\d+(\.\d{1,2})?$/,
      errorMessage: '请输入正确的价格格式'
    }]
  },
  dec: {
    rules: [{
      required: true,
      errorMessage: '请输入餐品描述'
    }]
  },
  packPrice: {
    rules: [{
      errorMessage: '请输入打包费'
    }, {
      pattern: /^\d+(\.\d{1,2})?$/,
      errorMessage: '请输入正确的打包费格式'
    }]
  },
  sendPrice: {
    rules: [{
      errorMessage: '请输入配送费'
    }, {
      pattern: /^\d+(\.\d{1,2})?$/,
      errorMessage: '请输入正确的配送费格式'
    }]
  }
};

const food = reactive({
  _id: null,
  name: '',
  price: '',
  dec: '',
  packPrice: '',
  sendPrice: ''
});
const imageUrl = ref('');
const isEditMode = ref(false);

// 操作按钮配置
const options1 = reactive([
  {
    text: "编辑",
    style: { backgroundColor: '#007AFF' }
  },
  {
    text: "删除",
    style: { backgroundColor: '#dd524d' }
  }
]);

// 图片处理
const loadDefaultAvatar = async () => {
  try {
    const module = await import('@/assets/mine/defaultFoodIcon.svg');
    imageUrl.value = module.default;
  } catch (error) {
    console.error('图片加载失败:', error);
  }
};

// 添加选择的图片临时路径存储
const selectUrl = ref('');

// 修改图片选择函数
const selectImage = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ["original", "compressed"],
    sourceType: ["album", "camera"],
    success: async (res) => {
      const tempFilePath = res.tempFilePaths[0];
      selectUrl.value = tempFilePath;  // 保存临时路径
      imageUrl.value = tempFilePath;   // 用于显示
    },
    fail: (err) => {
      console.error("选择图片失败：", err);
    }
  });
};


// 修改表单重置函数
const resetForm = () => {
  loadDefaultAvatar();
  isEditMode.value = false;
  selectUrl.value = '';  // 重置选择的图片
  food._id = null;
  Object.keys(food).forEach(key => {
    if (key !== '_id') food[key] = ''
  })
};

// 修改表单提交函数
const submit = async () => {

  // 确保图片已选择
  if (!selectUrl.value && !isEditMode.value) {
    uni.showToast({ title: '请选择餐品图片', icon: "error" });
    return;
  }

  try {
    const valid = await formRef.value.validate();
    if (!valid) {
      return;
    }
    let uploadResult = ''
    // 构建餐品信息参数
    let params = {
      sellerId: userStore.userId,
      name: food.name,
      price: Number(food.price),
      dec: food.dec,
      // icon: uploadResult, // 添加图片URL
      createTime: Date.now(),
      isDown: false,
      isPress: false,
      isDelete: false
    }
    // 先上传图片
    if (selectUrl.value) {
      uploadResult = await new Promise((resolve, reject) => {
        uni.uploadFile({
          url: baseUrl + '/users/uploadFoodIcon',
          filePath: selectUrl.value,
          name: 'file',
          formData: {
            userId: userStore.userId,
          },
          success: (uploadRes) => {
            const res = JSON.parse(uploadRes.data);
            if (res.code == '200') {
              resolve(res.path);
            } else {
              reject(new Error(res.message));
            }
          },
          fail: (err) => {
            reject(err);
          },
        });
      });

      params.icon = uploadResult;
    }


    if (food.packPrice) {
      params.packPrice = Number(food.packPrice)
    }
    if (food.sendPrice) {
      params.sendPrice = Number(food.sendPrice)
    }

    if (isEditMode.value) {
      console.log('food: ', food);
      // 执行更新操作
      updataFood({ ...params, id: food._id }).then(res => {
        if (res.code == 200) {
          uni.showToast({ title: '更新成功' });
          // 重置状态
          curNow.value = 1
          list.value = [...originalTabs]
          resetForm()
          // 重新获取用户信息, 拿取店家的餐品列表
          getCurrentUserInfo()
        } else {
          uni.showToast({
            title: '网络开了点小差~', icon: "error"
          });
        }
      }).catch(err => {
        uni.showToast({ title: '网络开了点小差~', icon: "error" });
      })
    } else {
      // 执行新增操作
      upFood(params).then(res => {
        if (res.code == 200) {
          // uni.showToast({ title: '上传成功, 等待审核~' });
          uni.showToast({ title: '上传成功~' });
          // 重置状态
          curNow.value = 1
          list.value = [...originalTabs]
          resetForm()
          // 重新获取用户信息, 拿取店家的餐品列表
          getCurrentUserInfo()
        } else {
          uni.showToast({ title: '网络开了点小差~', icon: "error" });
        }
      }).catch(err => {
        uni.showToast({ title: '网络开了点小差~', icon: "error" });
      })
    }
  } catch (error) {
    console.error('操作失败:', error);
    uni.showToast({
      title: '操作失败: ' + (error.message || '未知错误'),
      icon: 'error'
    });
  }
};

// 列表操作
const handleAction = (item, { index }) => {
  if (index === 0) editFood(item);
  if (index === 1) deleteGoods(item);
};

/**
 *  编辑商品
 */
const editFood = (item) => {
  curNow.value = 0;
  isEditMode.value = true;
  // 更新tab文字
  list.value = [{ name: '餐品编辑' }, list.value[1]]

  Object.keys(food).forEach(key => food[key] = item[key]);
  imageUrl.value = item.icon;
};

/**
 * 删除商品
 */
const deleteGoods = (item) => {
  deleteFood({ sellerId: userStore.userId, id: item._id }).then(res => {
    if (res.code == 200) {
      uni.showToast({ title: '删除成功' });
      // 重新获取用户信息, 拿取店家的餐品列表
      getCurrentUserInfo()
    } else {
      uni.showToast({ title: '网络开了点小差~', icon: "error" });
    }
  }).catch(err => {
    uni.showToast({ title: '网络开了点小差~', icon: "error" });
  })
};


// 初始化数据
const foodList = ref([{
  id: 1,
  name: '招牌牛肉面',
  price: 25.00,
  sendPrice: 3.00,
  packPrice: 1.00,
  dec: '精选牛腱肉，慢火熬制汤底，搭配手工拉面',
  icon: 'https://img95.699pic.com/photo/32118/3551.jpg_wh860.jpg'
}]); // 保持原有测试数据不变

// 获取店家餐品(排除掉删除的餐品)
foodList.value = userStore.userInfo.food.filter(item => !item.isDelete)

/**
 * 查询用户信息
 */
let getCurrentUserInfo = () => {
  if (userStore.userId) {
    getUserInfo({ userId: userStore.userId || '' }).then(res => {
      userStore.getInfo(res.userInfo)
      foodList.value = userStore.userInfo.food.filter(item => !item.isDelete)
    })
  }
}






</script>

<style lang="scss" scoped>
/* 保持原有样式不变 */
:deep(.u-swipe-action-item__right) {
  bottom: 20rpx;
}

page {
  background-color: white;
}

.content {
  height: calc(100vh - var(--window-top) - 100rpx);
  padding: 30rpx;
  background-color: white;
  overflow: auto;

  .main {
    uni-forms-item {
      margin-bottom: 30rpx;
    }

    .avatar {
      width: 200rpx;
      height: 200rpx;
      border: 2rpx solid #eee;
      border-radius: 8rpx;

      img {
        width: 100%;
        height: 100%;
        border-radius: 6rpx;
      }
    }

    button {
      margin-top: 40rpx;
      background-color: #007AFF;
    }
  }

  .food-list {
    .food-item {
      display: flex;
      padding: 20rpx;
      margin-bottom: 20rpx;
      background: #fff;
      border-radius: 12rpx;
      box-shadow:
        4rpx 8rpx 20rpx -8rpx rgba(0, 0, 0, 0.12),
        0 12rpx 24rpx -4rpx rgba(0, 0, 0, 0.08);

      .food-image {
        width: 200rpx;
        height: 200rpx;
        border-radius: 12rpx;
        margin-right: 20rpx;
      }

      .food-info {
        flex: 1;

        .food-name {
          font-size: 28rpx;
          color: #333;
          font-weight: 500;
        }

        .food-desc {
          width: 100%;
          font-size: 24rpx;
          color: #666;
          margin: 10rpx 0;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }

        .price-row {
          display: flex;
          justify-content: space-between;

          .price-item:first-child {
            color: #ff5000;
            font-weight: bold;
          }
        }
      }
    }
  }
}
</style>